package com.wang.designpattern.prototype.deepclone;

import java.io.*;

public class DeepPropotype implements Cloneable, Serializable {

    private static final long serialVersionUID = 1L;

    public String name;
    // 引用类型
    public DeepcloneTarget deepcloneTarget;

    public DeepPropotype() {
        super();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepcloneTarget getDeepcloneTarget() {
        return deepcloneTarget;
    }

    public void setDeepcloneTarget(DeepcloneTarget deepcloneTarget) {
        this.deepcloneTarget = deepcloneTarget;
    }

    // 深拷贝 方式1：clone
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        // 这里对基本数据类型属性和String的clone
        deep = super.clone();
        // 对引用类型属性，进行单独处理
        DeepPropotype deepPropotype = (DeepPropotype) deep;
        deepPropotype.deepcloneTarget = (DeepcloneTarget) deepcloneTarget.clone();
        return deepPropotype;
    }

    // 深拷贝 方式2：序列化
    public Object deepClone() {
        Object object = null;
        // 创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            // 序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            // 当前这个对象以对象流的方式输出
            oos.writeObject(this);
            // 反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            object = ois.readObject();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return object;
    }
}
